package clusteringTest;

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class CreateMapFromDic {

	/**
	 * @author wanyi
	 * 
	 */
	//为了格式一致，在小数点后加两个0
	public String changeToRightFormat (String s)
	{
		char[] array = s.toCharArray();
		char temp[] = new char[array.length + 100];
		int i = 0;
		int j = 0;
		for (i = 0; i < array.length; i++)
		{
			//加0
			if (array[i]=='.')
			{
				temp[j]=array[i];
				j++;
				temp[j]='0';
				j++;
				temp[j]='0';
				j++;
			}
			//加空格
			else if (array[i]==',')
			{
				temp[j]=array[i];
				j++;
				temp[j]=' ';
				j++;
			}
			else
			{
				temp[j]=array[i];
				j++;
			}
			
		}
		//"2:1.000, 17:1.000, 76:1.000, 96:1.000"
		String changedString = new String(temp);
		String resultString = changedString.substring(0,j);
		System.out.println(resultString + " end");
		return resultString;
	}
	//
	//public static HashMap<String, String> map = new HashMap<String,String>();
	
	public  HashMap<String,String> createMapFromDic (String dic)
	{
		
		Configuration conf = new Configuration ();
		HashMap<String, String> map = new HashMap<String,String>();
		
		try {
			    String record = null;
			    String key = null;
			    String value = null;
			    int space = 0;
			    int leftparentheses = 0;
			    int rightparentheses = 0;
			    FileSystem fs = FileSystem.get(URI.create(dic), conf);
			    FSDataInputStream in = null;
			    Path path = new Path(dic);
			    in = fs.open(path);
			    while ((record = in.readLine())!= null)
			    {
				    leftparentheses = record.indexOf("{");
				    rightparentheses = record.indexOf("}");
				    key = record.substring(leftparentheses+1,rightparentheses);
				    String changedKey = changeToRightFormat(key);
				    space = record.indexOf(" ");
					value = record.substring(0,space);
					map.put(changedKey, value);
					//System.out.println("Put: {" + key + "} , " + value + " into map.");
					System.out.println("Put: {" + changedKey + "}, " + value + " into map.");
			    }
			   
			    for (String val : map.values())
			    {
			    	System.out.println(val);
			    }
			    //System.out.println(map.get("7:1.000, 8:1.000, 41:1.000, 79:1.000, 83:1.000, 98:1.000"));
			    in.close();
			    fs.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//CreateMapFromDic cmd = new CreateMapFromDic();
		CreateMapFromDic  cmd  = new CreateMapFromDic();
		cmd.createMapFromDic("hdfs://localhost:9000/user/tuxinhui/clustering/dic");
		
	}

}
